import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';


const app = getApp();


Page({
    data: {
        show: false,
        showKey: false,
        newUserName: "",
        userName: "",
        nowKey: "",
        oldKey: "",
        admin: false,
        showAct: false,
        columns: [],
        switchAlliance: "",
        announcementShow: false
    },

    async onLoad() {
        const db = qq.cloud.database();
        const _ = db.command;
        let This = this;
        let columns = [];
        this.setData({ userName: app.data.userName });
        await db.collection("administer").where({
                unionId: app.data.unionId,
                alliance: app.data.alliance
            })
            .get()
            .then(res => {
                if (res.data.length) {
                    this.setData({ admin: true });
                }
            });
        await db.collection('key')
            .get()
            .then((res) => {
                res.data.map((value, index) => {
                    columns.push(value.alliance);
                })
            })
        this.setData({ columns: columns });
        this.setData({ switchAlliance: columns[0] });
    },
    onShareAppMessage() {
        qq.showShareMenu({
            showShareItems: ['qq', 'qzone', 'wechatFriends', 'wechatMoment']
        });
    },
    act() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        qq.navigateTo({
            url: '/pages/act/act'
        })
    },
    deletemember() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        qq.navigateTo({
            url: '/pages/deleteMember/deleteMember'
        })
    },
    async vacate() {
        const db = qq.cloud.database()
        const _ = db.command;
        let act = "";
        if (app.data.actTimestamp + 86400000 <= new Date().getTime()) {
            Toast("行动已超过24小时,无法请假");
            return;
        }
        await db.collection("act")
            .where({
                "alliance": app.data.alliance
            })
            .get()
            .then(res => {
                act = res.data[0].act.pop();

            });
        await Dialog.confirm({
                message: '是否确认请假',
            })
            .then(async() => {
                let onHook = "";
                await db.collection(app.data.whoSign)
                    .where({
                        unionId: _.eq(app.data.unionId),
                        "alliance": app.data.alliance
                    })
                    .get()
                    .then(res => {
                        try {
                            if (res.data[0][app.data.act] == '挂机') {
                                onHook = res.data[0][app.data.act];
                            }
                        } catch (e) {}
                    }).catch(res => {
                        Toast('请假失败');
                    })
                await db.collection(app.data.whoSign)
                    .where({
                        unionId: _.eq(app.data.unionId),
                        [app.data.act]: _.neq('挂机'),
                        "alliance": app.data.alliance
                    })
                    .update({
                        data: {
                            [act]: _.set("请假")
                        }
                    })
                    .then(res => {
                        if (onHook) {
                            Toast('判定挂机');
                        } else {
                            Toast('请假成功');
                        }
                    }).catch(res => {
                        Toast('请假失败');
                    })
            })
            .catch((error) => {});
    },
    async exportExcel() {
        const db = qq.cloud.database();
        let list = [];
        let act = ['userName'];
        let totalList = [];
        await db.collection("sign-in")
            .where({
                "alliance": app.data.alliance
            })
            .get()
            .then(res => {
                list = res.data;
            });
        await db.collection("controlSign-in")
            .where({
                "alliance": app.data.alliance
            })
            .get()
            .then(res => {
                res.data.map((value) => {
                    value.userName = value.userName + "(控)";
                    list.push(value);
                });
            });
        await db.collection("act")
            .where({
                "alliance": app.data.alliance
            })
            .get()
            .then(res => {
                for (let i = 0; i < res.data[0].act.length; i++) {
                    act.push(res.data[0].act[i]);
                }
                act.push("汇总");
            });

        for (let i = 0; i < list.length; i++) {
            let line = {};
            let count = 0;
            for (let j = 0; j < act.length; j++) {
                line[act[j]] = list[i][act[j]] ? list[i][act[j]] : "×";
                if (list[i][act[j]] === "√") {
                    count++;
                }
            }
            line["汇总"] = count.toString();
            totalList.push(line);
        }
        totalList = totalList.sort((a, b) => {
            let x = Number(a["汇总"]);
            let y = Number(b["汇总"]);
            return x > y ? -1 : x < y ? 1 : 0
        })
        qq.cloud.callFunction({
            name: 'excelExport',
            data: {
                list: totalList,
                act,
                alliance: app.data.alliance
            },
        }).then(res => {
            qq.cloud.downloadFile({
                fileID: res.result.fileID,
                success: res => {
                    qq.saveFile({
                        tempFilePath: res.tempFilePath,
                        success(res) {
                            qq.openDocument({
                                filePath: res.savedFilePath,
                                success(res) {},
                                fail(err) {}
                            })
                        }
                    })
                },
                fail: err => {
                    // handle error
                }
            });

        }).catch(err => {})

    },
    rename() {
        this.setData({ show: true });
    },
    async comfirm(event) {
        if (this.data.newUserName != "") {
            const db = qq.cloud.database()
            await db.collection(app.data.whoNumber)
                .where({
                    "alliance": app.data.alliance,
                    unionId: app.data.unionId
                })
                .update({
                    data: {
                        Name: this.data.newUserName
                    }
                })
                .then(res => {
                    if (res.stats.updated == 0) {
                        Toast('请勿改相同的名字');
                    } else if (res.stats.updated == 1) {
                        Toast('修改成功');
                    }
                }).catch(err => {
                    Toast('改名失败')
                })
            await db.collection(app.data.whoSign)
                .where({
                    unionId: app.data.unionId
                })
                .update({
                    data: {
                        userName: this.data.newUserName
                    }
                })
                .then(res => {
                    this.setData({ show: false });
                    this.setData({ userName: this.data.newUserName });
                    app.data.userName = this.data.newUserName;
                    this.setData({ newUserName: "" });
                }).catch(err => {
                    Toast('改名失败')
                })
        } else {
            Toast('名字不能为空')
        }
    },
    onClose(event) {
        this.setData({ show: false });
        this.setData({ newUserName: "" });
    },
    onChange(ev) {
        this.setData({ newUserName: ev.detail });
    },
    recover() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        qq.navigateTo({
            url: '/pages/recover/recover'
        })
    },
    setKey() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        this.setData({ showKey: true });
    },
    async comfirmKey(event) {
        if (this.data.newKey != "" && this.data.oldKey != "") {
            const db = qq.cloud.database();
            const _ = db.command;
            let admin = false;
            let haveKey = false;
            await db.collection('administer').where({
                unionId: _.eq(app.data.unionId)
            }).get().then((res) => {
                console.log(res);
                if (res.data.length != 0) {
                    admin = true
                }
            })
            await db.collection('key').where({
                key: _.eq(this.data.oldKey)
            }).get().then((res) => {
                if (res.data.length != 0) {
                    haveKey = true
                }
            }).catch((err) => {})
            await db.collection('key').where({
                key: _.eq(this.data.newKey)
            }).get().then((res) => {
                if ((res.data.length == 1)) {
                    haveKey = false;
                    return;
                }
            }).catch((err) => {})
            if (admin && haveKey) {
                await db.collection("key")
                    .where({
                        key: this.data.oldKey,
                        "alliance": app.data.alliance
                    })
                    .update({
                        data: {
                            key: this.data.newKey
                        }
                    })
                    .then(res => {
                        this.setData({ showKey: false });
                        this.setData({ newKey: "" });
                        this.setData({ oldKey: "" });
                        Toast('设置密钥成功')
                    }).catch(err => {
                        Toast('设置密钥失败')
                    })
            } else {
                Toast("修改失败");
            }
        } else {
            Toast("新老密钥不能为空");
        }
    },
    onCloseKey(event) {
        this.setData({ showKey: false });
        this.setData({ oldKey: "" });
        this.setData({ newKey: "" });
    },
    onChangeKey(ev) {
        if (ev.currentTarget.dataset.key == 'old') {
            this.setData({ oldKey: ev.detail });
        } else if (ev.currentTarget.dataset.key == 'new') {
            this.setData({ newKey: ev.detail });
        }
    },
    retroactive() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        qq.navigateTo({
            url: '/pages/retroactive/retroactive'
        })
    },
    onHook() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        qq.navigateTo({
            url: '/pages/onHook/onHook'
        })
    },
    group() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        qq.navigateTo({
            url: '/pages/group/group'
        })
    },
    deleteAct() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        qq.navigateTo({
            url: '/pages/deleteAct/deleteAct'
        })
    },
    sprog() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        qq.navigateTo({
            url: '/pages/sprog/sprog'
        })
    },
    errorSign() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        qq.navigateTo({
            url: '/pages/errorSign/errorSign'
        })
    },
    managePrivilege() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        qq.navigateTo({
            url: '/pages/managePrivilege/managePrivilege'
        })
    },
    empty() {
        const db = qq.cloud.database();
        const _ = db.command;
        let admin = false;
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        Dialog.confirm({
                title: '严重警告',
                message: '一旦按下确认，成员数据、作战数据、行动数据将全部清空，无法恢复。请谨慎使用！！！(管理资料以及黑名单依旧存在)',
            })
            .then(async() => {
                await db.collection('sign-in').where({
                    alliance: app.data.alliance
                }).remove().then((res) => {});
                await db.collection('controlSign-in').where({
                    alliance: app.data.alliance
                }).remove().then((res) => {});
                await db.collection('member').where({
                    alliance: app.data.alliance
                }).remove().then((res) => {})
                await db.collection('controlMember').where({
                    alliance: app.data.alliance
                }).remove().then((res) => {})
                await db.collection('act').where({
                    alliance: app.data.alliance
                }).update({
                    data: {
                        act: ["初始化行动"],
                        antistop: [""],
                        timestamp: [""]
                    }
                }).then((res) => {})
                Toast('操作成功');
            })
            .catch(() => {
                // on cancel
            });
    },
    async switchAlliance() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        if (app.data.controlNumber) {
            Toast('控号模式无法切换联盟');
            return
        }
        const db = qq.cloud.database();
        const _ = db.command;
        let uniqueAdmin = false;
        await db.collection("administer").where({
                unionId: app.data.unionId,
                unique: '1'
            })
            .get()
            .then(res => {
                if (res.data.length) {
                    uniqueAdmin = true;
                }
            });
        if (!uniqueAdmin) {
            Toast("特殊人员专用");
            return
        }
        this.setData({ showAct: true });
    },
    onClickLeft() {
        this.setData({ showAct: false });
    },
    async onClickRight() {
        const db = qq.cloud.database();
        const _ = db.command;
        await db.collection("administer")
            .where({
                unionId: app.data.unionId,
                alliance: app.data.alliance
            })
            .update({
                data: {
                    alliance: this.data.switchAlliance
                }
            })
            .then(res => {}).catch(err => {});
        await db.collection("member")
            .where({
                unionId: app.data.unionId,
                alliance: app.data.alliance
            })
            .update({
                data: {
                    alliance: this.data.switchAlliance
                }
            })
            .then(res => {}).catch(err => {});
        await db.collection("sign-in")
            .where({
                unionId: app.data.unionId,
                alliance: app.data.alliance
            })
            .update({
                data: {
                    alliance: this.data.switchAlliance
                }
            })
            .then(res => {
                Toast('切换成功');
                app.data.alliance = this.data.switchAlliance;
            }).catch(err => {
                Toast('切换失败')
            })
        await db.collection("act")
            .where({
                alliance: app.data.alliance
            })
            .get()
            .then(res => {
                app.data.act = res.data[0].act.pop();
            }).catch(err => {
                Toast('切换失败')
            })
        this.setData({ showAct: false });
    },
    onChangeAlliance(event) {
        const { picker, value, index } = event.detail;
        this.setData({ switchAlliance: value });
    },
    userSwitch() {
        if (!this.data.admin) {
            Toast("没有管理员权限");
            return
        }
        qq.navigateTo({
            url: '/pages/userSwitch/userSwitch'
        })
    },
    announcement() {
        this.setData({ announcementShow: true });
    },
    announcementClose() {
        this.setData({ announcementShow: false });
    },
    userDel() {
        const db = qq.cloud.database();
        const _ = db.command;
        Dialog.confirm({
                title: '严重警告',
                message: '一旦按下确认，自身所有数据将会删除',
            })
            .then(async() => {
                if (app.data.controlNumber) {
                    db.collection('controlMember').where({
                        Name: app.data.userName,
                        unionId: app.data.unionId
                    }).remove().then(res => {})
                    db.collection('controlSign-in').where({
                        userName: app.data.username,
                        unionId: app.data.unionId
                    }).remove().then(res => {
                        Toast('删除成功');
                        setTimeout(() => {
                            qq.navigateTo({
                                url: '/pages/register/register'
                            })
                        }, 3000);
                    })
                } else {
                    db.collection('member').where({
                        Name: app.data.userName,
                        unionId: app.data.unionId
                    }).remove().then(res => {
                        console.log(res);
                    })
                    db.collection('sign-in').where({
                        userName: app.data.userName,
                        unionId: app.data.unionId
                    }).remove().then(res => {
                        console.log(res);
                        Toast('删除成功');
                        setTimeout(() => {
                            qq.reLaunch({
                                url: '/pages/register/register'
                            });
                        }, 3000);
                    })
                }
            }).catch((err) => {
                console.log(err);
            });
    }
})